package com.fg.cloud.manager.service.order.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.fg.cloud.common.NumberUtil;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.common.finals.FlowStatus;
import com.fg.cloud.common.finals.OrderStatus;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.manager.entry.BaseEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyAreaVo;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.agency.vo.AgencyVo;
import com.fg.cloud.manager.entry.factory.FactoryProcessEntity;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.entry.order.OrderCheckEntity;
import com.fg.cloud.manager.entry.order.OrderDetailEntity;
import com.fg.cloud.manager.entry.order.OrderInfoEntity;
import com.fg.cloud.manager.entry.order.vo.OrderDetailVo;
import com.fg.cloud.manager.entry.order.vo.OrderInfoVo;
import com.fg.cloud.manager.entry.product.ProductSkuEntity;
import com.fg.cloud.manager.entry.product.vo.ProductSkuVo;
import com.fg.cloud.manager.entry.product.vo.UnitVo;
import com.fg.cloud.manager.entry.system.InvoiceManageEntity;
import com.fg.cloud.manager.mapper.BaseMapper;
import com.fg.cloud.manager.mapper.agency.AgencyAreaMapper;
import com.fg.cloud.manager.mapper.agency.AgencyCartMapper;
import com.fg.cloud.manager.mapper.agency.AgencyMapper;
import com.fg.cloud.manager.mapper.factory.FactoryProcessMapper;
import com.fg.cloud.manager.mapper.order.OrderCheckMapper;
import com.fg.cloud.manager.mapper.order.OrderDetailMapper;
import com.fg.cloud.manager.mapper.order.OrderInfoMapper;
import com.fg.cloud.manager.mapper.product.ProductSkuMapper;
import com.fg.cloud.manager.mapper.system.InvoiceManageMapper;
import com.fg.cloud.manager.service.BaseServiceImpl;
import com.fg.cloud.manager.service.order.OrderInfoService;

/**
 * @author ：
 * @date ： 2017年6月21日 下午5:32:16
 * @Desc ：订单
 */
@Service
public class OrderInfoServiceImpl extends BaseServiceImpl implements OrderInfoService {

	@Autowired
	private OrderInfoMapper orderMapper ;
	@Autowired
	private OrderDetailMapper detailMapper ;
	@Autowired
	private OrderCheckMapper checkMapper ; 
	@Autowired
	private FactoryProcessMapper  processMapper ;
	@Autowired
	private AgencyMapper agencyMapper ; 
	@Autowired
	private ProductSkuMapper skuMapper ;
	@Autowired
	private InvoiceManageMapper invoiceMapper ;
	@Autowired
	private AgencyCartMapper cartMapper ; 
	Long userId = null ;
	Long facId = null ; 
	String userName = null; 
	
	@Override
	protected <T extends BaseEntity> BaseMapper getBaseMapper() {
		return orderMapper;
	}
	
	/**
	 * 订单搜索
	 */
	@Override
	public void findList(PageUtils<BaseEntity> pageInfo, String search,
			Long areaId,String areaNumber,String statusStr,List<String> areaNumberList) {
		long total = orderMapper.filterCount(pageInfo, search,areaId,areaNumber,statusStr,areaNumberList);
		pageInfo.setTotal(total);
		if (total > 0) {
			pageInfo.setData(orderMapper.findList(pageInfo, search,areaId,areaNumber,statusStr,areaNumberList));
		} else {
			pageInfo.setData(new ArrayList<BaseEntity>());
		}
	}

	/**
	 * 查询订单条数
	 */
	@Override
	public int getCount(PageUtils<BaseEntity> pageInfo, String search,Long areaId,String areaNumber
			,String statusStr,List<String> areaNumberList) {
		return orderMapper.filterCount(pageInfo, search,areaId,areaNumber,statusStr,areaNumberList);
	}

	/**
	 * 厂商端新增订单
	 */
	@Transactional
	@Override
	public Result addOrder(OrderInfoEntity order) throws ServiceException{
		getLoginInfo();
		if(order == null || order.getFacId() == null || order.getAgeId() == null ){
			throw new ServiceException(StatusCode.LACKVALUE,"订单信息、订单编号、经销商和订单商品不能为空");
		}
		if(null == order.getListDetails() || 0 == order.getListDetails().size()){
			throw new ServiceException(StatusCode.LACKVALUE,"订单商品不能为空");
		}
		for(OrderDetailEntity detail : order.getListDetails()){
			if(detail.getSkuId() == null || detail.getProductId() == null ||detail.getProductId() <0  
					|| StringUtils.isEmpty(detail.getProductName())  
					|| StringUtils.isEmpty(detail.getProductNumber())){
				throw new ServiceException(StatusCode.LACKVALUE,"订单商品、商品名称和商品编码不能为空");
			}
		}
		Result resultStr = validateProduct(order, "factory");
		if(!resultStr.isSuccess()){
			throw new ServiceException(StatusCode.EXCEPTIONERROR,resultStr.getData()+":"+resultStr.getMessage());
		}
		order.setNeedPay(order.getAmountPay());
		order.setOrderSource(1);
		order.setOrderStatus(0);
		order.setOrderDate(new Date());
		//order.setDeliveryDate(DateUtil.stringToDate(order.getDeliveryDateStr(), DateUtil.DATE_TO_STRING_SHORT_PATTERN));
		order.setCreator(userId);
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		//编码规则
		order.setOrderNo(NumberUtil.getOrderNumber());
		int flag = orderMapper.insert(order);
		if(flag == 0){
			throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
		}
		for(OrderDetailEntity detail : order.getListDetails()){
			detail.setOrderId(order.getId());
			flag = detailMapper.insert(detail);
			if(flag == 0){
				throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
			}
		}
		OrderCheckEntity checkEntity = setCheckData(order.getId(),FlowStatus.ORDERCREATE,order.getOrderNo()) ;
		checkMapper.insert(checkEntity);
		return Result.result(null, true, StatusCode.SAVESUCCESS, "订单信息保存成功");
	}

	/**
	 * 修改订单
	 */
	@Override
	@Transactional
	public Result modifyOrder(OrderInfoEntity order) throws ServiceException {
		getLoginInfo();
		BigDecimal amountTotal = new BigDecimal(0) ;
		if(order == null || StringUtils.isEmpty(order.getOrderNo()) || order.getFacId() == null || order.getAgeId() == null ){
			throw new ServiceException(StatusCode.LACKVALUE,"订单信息、订单编号、经销商和订单商品不能为空");
		}
		if(null == order.getListDetails() || 0 == order.getListDetails().size()){
			throw new ServiceException(StatusCode.LACKVALUE,"订单商品不能为空");
		}
		AgencyVo agencyVo = agencyMapper.selectAgencyInfo(order.getAgeId(),facId);
		for(OrderDetailEntity detail : order.getListDetails()){
			if(detail.getSkuId() == null || detail.getProductId() == null ||detail.getProductId() <0  
					|| StringUtils.isEmpty(detail.getProductName())  
					|| StringUtils.isEmpty(detail.getProductNumber())){
				throw new ServiceException(StatusCode.LACKVALUE,"订单商品、商品名称和商品编码不能为空");
			}
		}
		int flag = 0 ;
		for(OrderDetailEntity detail : order.getListDetails()){
			BigDecimal discount = agencyVo.getDiscount(); 
			detail.setPromotionPrice(detail.getSellPrice().multiply(discount).divide(new BigDecimal(100)));
			detail.setSumMoney(detail.getPromotionPrice().multiply(detail.getAmount()));
			amountTotal = amountTotal.add(detail.getSumMoney());
			flag = detailMapper.update(detail);
			if(flag < 0){
				throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
			}
		}
		order.setAmountTotal(amountTotal);
		order.setAmountPay(amountTotal.add(order.getExpressFee()));
		//order.setDeliveryDate(DateUtil.stringToDate(order.getDeliveryDateStr(), DateUtil.DATE_TO_STRING_SHORT_PATTERN));
		order.setUpdater(userId);
		order.setUpdateTime(new Date());
		flag = orderMapper.update(order);
		if(flag < 0){
			throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
		}
		OrderCheckEntity checkEntity = setCheckData(order.getId(),FlowStatus.MODIFY,order.getOrderNo()) ;
		checkMapper.insert(checkEntity);
		return Result.result(null, true, StatusCode.SAVESUCCESS, "修改成功");
	}

	/**
	 * 订单审核
	 */
	@Transactional
	@Override
	public int checkOrder(String[] ids) {
		getLoginInfo();
		FactoryProcessEntity process = processMapper.selectByfacId(facId);
		String checkName = "" ; // 订单操作名称
		int status = 0 ;
		checkName = FlowStatus.BUSINESSAUDIT;
		if(process.getFinanceReview()  == 0 ){
			status = OrderStatus.FINANCEREVIEW;
		}
		if(process.getFinanceReview() == 1 && process.getShipConfirm() == 0){
			status = OrderStatus.PENDINGSHIP;
		}
		if(process.getFinanceReview() == 1 && process.getShipConfirm() == 1 
				&& process.getReceivingConfirm() == 0){
			status = OrderStatus.PENDINGRECIPIENT;
		}
		if(process.getFinanceReview() == 1 && process.getShipConfirm() == 1 
				&& process.getReceivingConfirm() == 1){
			status = OrderStatus.COMPLETE;
		}
		//添加订单操作记录
		for(String id:ids){
			OrderInfoEntity order = orderMapper.find(Long.parseLong(id));
			OrderCheckEntity checkEntity = setCheckData(Long.parseLong(id),checkName,order.getOrderNo()) ;
			checkMapper.insert(checkEntity);
		}
		return orderMapper.checkOrder(status, ids);
	}

	/**
	 * 财务审核
	 */
	@Override
	public int financialAudit(String []ids){
		getLoginInfo();
		FactoryProcessEntity process = processMapper.selectByfacId(facId);
		String checkName = "" ; // 订单操作名称
		int status = 0 ;
		checkName = FlowStatus.FINANCEREVIEW;
		if(process.getShipConfirm() == 0){
			status = OrderStatus.PENDINGSHIP;
		}
		if(process.getShipConfirm() == 1 && process.getReceivingConfirm() == 0){
			status = OrderStatus.PENDINGRECIPIENT;
		}
		if( process.getShipConfirm() == 1 && process.getReceivingConfirm() == 1){
			status = OrderStatus.COMPLETE;
		}
		for(String id:ids){
			OrderInfoEntity order = orderMapper.find(Long.parseLong(id));
			OrderCheckEntity checkEntity = setCheckData(Long.parseLong(id),checkName,order.getOrderNo()) ;
			checkMapper.insert(checkEntity);
		}
		return orderMapper.checkOrder(status, ids);
	}
	
	/**
	 * 业务反审核
	 */
	@Override
	@Transactional
	public int reverseOrder(String[] ids,String remark ){
		getLoginInfo();
		for(String id:ids){
			OrderInfoEntity order = orderMapper.find(Long.parseLong(id));
			OrderCheckEntity checkEntity = setCheckData(Long.parseLong(id),FlowStatus.REVERSE,order.getOrderNo()) ;
			checkMapper.insert(checkEntity);
		}
		return orderMapper.reverseOrder(ids,remark);
	}

	/**
	 * 逻辑删除订单
	 */
	@Override
	@Transactional
	public int delOrder(String[] ids) {
		getLoginInfo();
		for(String id:ids){
			OrderInfoEntity order = orderMapper.find(Long.parseLong(id));
			OrderCheckEntity checkEntity = setCheckData(Long.parseLong(id),FlowStatus.DELETE,order.getOrderNo()) ;
			checkMapper.insert(checkEntity);
		}
		return orderMapper.delOrder(ids);
	}
	
	/**
	 * Description:给流程节点实体赋值
	 * @param orderId 订单ID
	 * @param checkName 流程节点名称
	 * @return
	 * @author liushengchao
	 * @date  2017年9月5日上午9:09:37
	 */
	public OrderCheckEntity setCheckData(Long orderId,String checkName,String orderNo){
		OrderCheckEntity checkEntity = new OrderCheckEntity() ;
		checkEntity.setOrderId(orderId);
		checkEntity.setFacId(facId);
		checkEntity.setCheckUserId(userId);
		checkEntity.setCheckUser(userName);
		checkEntity.setCheckName(checkName);
		checkEntity.setCheckDate(new Date());
		return checkEntity ;
	}
	
	/**
	 * Description:厂商端获取登录人信息
	 * @author liushengchao
	 * @date  2017年9月11日上午9:07:35
	 */
	public void getLoginInfo(){
		userId = ((FactoryUserVo)UserUtils.getCurrentUser()).getId();
		facId = ((FactoryUserVo)UserUtils.getCurrentUser()).getFacId(); 
		userName = ((FactoryUserVo)UserUtils.getCurrentUser()).getUserName(); 
	}

	/**
	 * 查询订单头，分页
	 */
	@Override
	public void findList(PageUtils<OrderInfoEntity> pageinfo) {
		long count = orderMapper.findCountByOrderInfo(pageinfo);
		pageinfo.setTotal(count);
		if (count > 0) {
			pageinfo.setData(orderMapper.findByOrderInfo(pageinfo));
		} else {
			pageinfo.setData(new ArrayList<OrderInfoEntity>());
		}
	}

	/**
	 * 经销商端订单新增
	 */
	@Override
	@Transactional
	public Result AgencyInsertOrder( OrderInfoVo order,String type) {
		AgencyUserVo user = (AgencyUserVo)UserUtils.getCurrentUser();
		userId = user.getId();
		facId = user.getFacId();
		userName = user.getUserName();
		if(order == null || order.getFacId() == null || order.getAgeId() == null ){
			throw new ServiceException(StatusCode.LACKVALUE,"订单信息、经销商不能为空");
		}
		List<OrderDetailEntity> orderDetailList = order.getListDetails();
		if(null == orderDetailList || 0 == orderDetailList.size()){
			throw new ServiceException(StatusCode.LACKVALUE,"订单商品不能为空");
		}
		List<Long> cartIds = new ArrayList<>();
		for(int i =0 ;i < orderDetailList.size() ; i ++ ){
			OrderDetailEntity detail = orderDetailList.get(i);
			if(detail.getSkuId() == null ||  StringUtils.isEmpty(detail.getProductName())  
					|| StringUtils.isEmpty(detail.getProductNumber())){
				throw new ServiceException(StatusCode.LACKVALUE,"订单商品、商品名称或商品编码不能为空");
			}
			if(detail.getId() != null) {
				cartIds.add(detail.getId());
				detail.setId(null);
			}
		}
		if("save".equals(type)){
			order.setOrderStatus(9);
		}else{
			order.setOrderStatus(0);
			order.setListDetails(orderDetailList);
			Result resultStr = validateProduct(order, "agency");
			if(!resultStr.isSuccess()){
				throw new ServiceException(StatusCode.EXCEPTIONERROR,resultStr.getData()+":"+resultStr.getMessage());
			}
		}
		order.setNeedPay(order.getAmountPay());
		order.setOrderSource(0);
		order.setOrderDate(new Date());
		order.setCreator(userId);
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		//编码规则
		order.setOrderNo(NumberUtil.getOrderNumber());
		int flag = orderMapper.insert(order);
		if(flag == 0){
			throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
		}
		for(OrderDetailEntity detail : orderDetailList){
			detail.setOrderId(order.getId());
			flag = detailMapper.insert(detail);
			if(flag == 0){
				throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
			}
		}
		if(cartIds.size() > 0){
			Long[] ids = new Long[cartIds.size()];
			cartIds.toArray(ids);
			long res = cartMapper.deletes(order.getAgeId(), ids);
			if(res == 0){
				throw new ServiceException(StatusCode.EXCEPTIONERROR,"删除购物车商品失败。");
			}
		}
		if("addOrder".equals(type)){
			OrderCheckEntity checkEntity = setCheckData(order.getId(),FlowStatus.ORDERCREATE,order.getOrderNo()) ;
			checkMapper.insert(checkEntity);	
		}
		return Result.result(null, true, StatusCode.SAVESUCCESS, "订单信息保存成功");
	}
	
	/**
	 * Description:验证商品价格变动和库存
	 * @param orderInfo
	 * @param Type
	 * @return
	 * @author liushengchao
	 * @date  2017年9月11日上午11:05:22
	 */
	public Result validateProduct(OrderInfoEntity orderInfo,String Type){
		try {
			Integer stockZeroFlag = 0 ;
			BigDecimal taxRate = null;
			if (0 == orderInfo.getInvoiceId()) 
				taxRate = BigDecimal.ZERO;
			else {
				InvoiceManageEntity invoice = invoiceMapper.find(orderInfo.getInvoiceId());
				taxRate = invoice.getTaxRate();
			}
			if("agency".equals(Type)){
				AgencyUserVo user = (AgencyUserVo)UserUtils.getCurrentUser();
				stockZeroFlag = user.getStockSetup().getZeroFlag();
			}else if("factory".equals(Type)){
				FactoryUserVo user = (FactoryUserVo)UserUtils.getCurrentUser() ;
				stockZeroFlag = user.getZeroFlag();
			}
			boolean stockFlag = false;
			boolean priceFlag = false;
			String stockStr = "【 ";
			String priceStr = "【 ";
			AgencyVo agencyVo = agencyMapper.selectAgencyInfo(orderInfo.getAgeId(),facId);
			BigDecimal discount = agencyVo.getDiscount().multiply(BigDecimal.valueOf(0.01));
			List<OrderDetailEntity> listDetails =  orderInfo.getListDetails();
			BigDecimal totalMoney = BigDecimal.ZERO;
			List<Map<String,Long>> orderDetList = new ArrayList<Map<String,Long>>();
			List<ProductSkuVo> productList = new ArrayList<>();
			for( int i = 0; i < listDetails.size(); i +=20  ){
				List<OrderDetailEntity> newList ;
				if(listDetails.size() <= 20){
					newList = listDetails;
				}else{
					newList = listDetails.subList(i, i + 20 );
				}
				for(int j = 0 ; j < newList.size() ; j ++){
					Map<String,Long> orderDet = new HashMap<String, Long>();
					orderDet.put("skuId", newList.get(j).getSkuId());
					orderDetList.add(orderDet);
				}
				List<ProductSkuVo> skuList = skuMapper.selectForOder(orderDetList, orderInfo.getAgeId()
						,Agency.getTableName(facId));
				productList.addAll(skuList);
			}
			//订单明细的库存与价格校验
			
			for(int i = 0 ; i < listDetails.size() ; i ++ ){
				OrderDetailEntity detail = listDetails.get(i);
				BigDecimal promotPrice = BigDecimal.ZERO ;
				BigDecimal changeNum = BigDecimal.ONE;
				for(int j = 0 ; j < productList.size() ; j ++ ){
					BigDecimal customPrice = BigDecimal.ZERO ;
					ProductSkuVo  newSku  = productList.get(j);
					//如果订单详情跟查询出商品不匹配则执行下一个循环。
					if(newSku.getId().intValue()!=detail.getSkuId().intValue()) continue;
					List<UnitVo> unitList = newSku.getUnitList();
					for(UnitVo unit : unitList){
						if(newSku.getId().longValue() == detail.getSkuId().longValue() && 
								unit.getId().longValue() == detail.getUnitId().longValue()){
							changeNum = new BigDecimal(unit.getNum());
							customPrice = unit.getCustomPrice();
							break ;
						}
					}
					if(newSku.getSpecialPrice() == null || newSku.getSpecialPrice().compareTo(BigDecimal.ZERO)==0  ){
						if(newSku.getUnitList() == null || newSku.getUnitList().size() == 0 ){
							promotPrice = newSku.getProductPrice().multiply(discount).multiply(changeNum).setScale(2, BigDecimal.ROUND_HALF_UP) ;
						}else{
							if(customPrice.compareTo(BigDecimal.ZERO) > 0){
								promotPrice = customPrice.multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP) ;
							}else{
								promotPrice = newSku.getProductPrice().multiply(discount).multiply(changeNum).setScale(2, BigDecimal.ROUND_HALF_UP) ;
							}
						}
					}else{
						promotPrice = newSku.getSpecialPrice().multiply(changeNum).setScale(2, BigDecimal.ROUND_HALF_UP) ;
					}
					
					BigDecimal taxPrice = promotPrice.add(promotPrice.multiply(taxRate)).setScale(2, BigDecimal.ROUND_HALF_UP);
					//计算当条商品总数量
					BigDecimal stdAmount = detail.getAmount() == null ? BigDecimal.ONE : detail.getAmount();
					//判断该商品的库存是否充足
					if( newSku.getStock().compareTo(stdAmount)== -1 && 0 == stockZeroFlag   ){
						stockFlag = true;
						stockStr = stockStr.concat( ((Integer)(i+1)).toString() ).concat("."+listDetails.get(i).getProductName()+" ");	
					}
					//判断该商品价格是否有变动
					if ( detail.getPromotionPrice().compareTo(taxPrice) != 0 ) {
						priceFlag = true;			
						priceStr = priceStr.concat( ((Integer)(i+1)).toString() ).concat("."+detail.getProductName()+" ");
						listDetails.get(i).setPromotionPrice(promotPrice.multiply(discount));
					}	
					//统计总金额
					totalMoney = totalMoney.add(taxPrice.multiply(stdAmount)).setScale(2, BigDecimal.ROUND_HALF_UP);
				}
			}
			//这是库存不足的情况
			if ( stockFlag ) {
				return Result.result(stockStr.concat("】"), false, StatusCode.FINDSUCCESS, "库存不足，无法下单！");
			}
			//这是价格变动的情况
			if ( priceFlag ) {
				return Result.result(stockStr.concat("】"), false, StatusCode.FINDSUCCESS, "商品价格已更新，订单价格异常！");
			}
			//特批价格
			if(1==orderInfo.getIsSpecialPrice() ){
				//对订单总金额的校验
				if ( totalMoney.compareTo(orderInfo.getAmountTotal()) !=0 ) {
					return Result.result("", false, StatusCode.FINDSUCCESS, "订单总金额有误！");
				}
				orderInfo.setAmountTotal(totalMoney);
				orderInfo.setAmountPay(orderInfo.getSpecialPrice().add(orderInfo.getExpressFee()).setScale(2, BigDecimal.ROUND_HALF_UP));	
			}else{
				//对订单总金额的校验
				if (totalMoney.compareTo(orderInfo.getAmountTotal()) !=0 ) {
					return Result.result("", false, StatusCode.FINDSUCCESS, "订单总金额有误！");
				}
				orderInfo.setAmountPay(totalMoney.add(orderInfo.getExpressFee()));
				orderInfo.setAmountTotal(totalMoney);
			}
			orderInfo.setListDetails(listDetails);
			return Result.result("", true, StatusCode.FINDSUCCESS, "验证通过");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.result("", false, StatusCode.EXCEPTIONERROR, e.getMessage());
		}
	}

	/**
	 * 经销商端订单修改
	 */
	@Override
	public Result AgencyModifyOrder(OrderInfoEntity order) {
		BigDecimal amountTotal = new BigDecimal(0) ;
		if(order == null || StringUtils.isEmpty(order.getOrderNo()) 
				|| order.getFacId() == null || order.getAgeId() == null ){
			throw new ServiceException(StatusCode.LACKVALUE,"订单信息、订单编号、经销商和订单商品不能为空");
		}
		if(null == order.getListDetails() || 0 == order.getListDetails().size()){
			throw new ServiceException(StatusCode.LACKVALUE,"订单商品不能为空");
		}
		AgencyVo agencyVo = agencyMapper.selectAgencyInfo(order.getAgeId(),facId);
		for(OrderDetailEntity detail : order.getListDetails()){
			if(detail.getSkuId() == null || detail.getProductId() == null ||detail.getProductId() <0  
					|| StringUtils.isEmpty(detail.getProductName())  
					|| StringUtils.isEmpty(detail.getProductNumber())){
				throw new ServiceException(StatusCode.LACKVALUE,"订单商品、商品名称和商品编码不能为空");
			}
		}
		int flag = 0 ;
		for(OrderDetailEntity detail : order.getListDetails()){
			BigDecimal discount = agencyVo.getDiscount(); 
			detail.setPromotionPrice(detail.getSellPrice().multiply(discount).divide(new BigDecimal(100)));
			detail.setSumMoney(detail.getPromotionPrice().multiply(detail.getAmount()));
			amountTotal = amountTotal.add(detail.getSumMoney());
			flag = detailMapper.update(detail);
			if(flag < 0){
				throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
			}
		}
		order.setAmountTotal(amountTotal);
		order.setAmountPay(amountTotal.add(order.getExpressFee()));
		order.setNeedPay(order.getAmountPay());
		//order.setDeliveryDate(DateUtil.stringToDate(order.getDeliveryDateStr(), DateUtil.DATE_TO_STRING_SHORT_PATTERN));
		order.setUpdater(userId);
		order.setUpdateTime(new Date());
		flag = orderMapper.update(order);
		if(flag < 0){
			throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序异常");
		}
		return Result.result(null, true, StatusCode.SAVESUCCESS, "修改成功");
	}
	
	/**
	 * 订单作废
	 */
	public int CancelOrder(String[] ids,String remark){
		getLoginInfo();
		String checkName = "" ; // 订单操作名称
		checkName = FlowStatus.CANCEL;
		//添加订单操作记录
		for(String id:ids){
			OrderInfoEntity order = orderMapper.find(Long.parseLong(id));
			OrderCheckEntity checkEntity = setCheckData(Long.parseLong(id),checkName,order.getOrderNo()) ;
			checkMapper.insert(checkEntity);
		}
		return orderMapper.cancelOrder(ids,remark);
	}
	
	/**
	 * 订单修改后保存并审核
	 */
	@Override
	@Transactional
	public Result saveAndCheck(OrderInfoEntity order){
		if(StringUtils.isEmpty(order.getId().toString())){
			throw new ServiceException(StatusCode.LACKVALUE,"订单编号不能为空");
		}
		int flag = 0 ;
		Result saveReslut = modifyOrder(order);
		if(saveReslut.isSuccess()){
			String[] ids = order.getId().toString().split(",");
			if(order.getOrderStatus()==0){
				flag = checkOrder(ids);
				if(flag == 0 ){
					throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序执行异常");
				}
				return Result.result(null, true, StatusCode.OPERATIONSUCCESS, "审核成功");
			}else if(order.getOrderStatus()==1){
				flag = financialAudit(ids);
				if(flag == 0 ){
					throw new ServiceException(StatusCode.EXCEPTIONERROR,"程序执行异常");
				}
				return Result.result(null, true, StatusCode.OPERATIONSUCCESS, "审核成功");
			}else{
				return Result.result(null, false, StatusCode.OPERATIONERROR, "该状态订单不能审核");
			}
		}else{
			return saveReslut ;
		}
	}
	
	public int updateStock(OrderDetailEntity detail){
		int amount = detail.getAmount().intValue();
		Long skuId = detail.getSkuId();
		ProductSkuEntity skuInfo = skuMapper.find(skuId);
		int newStock = skuInfo.getStock() - amount ; 
		skuInfo.setStock(newStock);
		return skuMapper.update(skuInfo);
	}

	//重置订单信息
	@Override
	@Transactional
	public boolean deleteOrder(Long facId) {
		//1.删除订单日志
		long r1 = checkMapper.deleteByFacId(facId);
		if ( r1 <= 0 ) return false ;
		//2.删除订单详情
		long r2 = detailMapper.delByFacId(facId);
		if ( r2 <= 0 ) return false ;
		//3.删除订单附件
		long r3 = orderMapper.delOrderFile(facId);
		if ( r3 <= 0 ) return false ;
		//4.删除订单
		long r4 = orderMapper.delByFacId(facId);
		
		if ( r1>0 && r2>0 && r3>0 && r4>0 ) {
			return true;
		}
		return false;
	}

	@Override
	public List<OrderDetailVo> findProductForOrderCopy(String tableName, List<String> skuIds,Long ageId) {
		List<OrderDetailVo> OrderProductList = orderMapper.findProductForOrderCopy(tableName, skuIds,ageId);
		if(OrderProductList.isEmpty()){
			return null ;
		}
		for(OrderDetailVo orderProduct : OrderProductList){
			orderProduct.setBasicPrice(orderProduct.getPromotionPrice());
		}
		return OrderProductList ;
	}
	
}
